/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-30
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-08
 * @Description: 
 */
/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-30
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-08
 * @Description: 数据本地读写 ，单例模式
 */
import 'package:chat_client/repositories/hive_repository.dart';

import 'package:chat_client/models/apply.dart'; // 申请
import 'package:chat_client/models/contact.dart'; //联系人
import 'package:chat_client/models/group.dart'; // 群组
import 'package:chat_client/models/conversation.dart';
import 'package:hive/hive.dart'; //聊天列表

/// 会话本地存储
class ConversationRepository {
  // 单例
  ConversationRepository._internal();
  static final ConversationRepository _instance =
      ConversationRepository._internal();
  static ConversationRepository get instance => _instance;

  // hive 实例
  final _hive = HiveService.instance;

  // 打开数据库
  late final Box _conversationBox;

  Future<void> _init() async {
    _conversationBox = await _hive.openBox('conversation');
  }

  // 储存会话
  Future<void> createOrUpdateConversation(
      Map<String, dynamic> conversations) async {
    await _init(); // 确保数据库已打开
    conversations.forEach((key, value) {
      _hive.createOrUpdate(_conversationBox, key, value);
    });
  }

  // 为会话增加消息
  Future<void> createMessage(sessionId, newMessage) async {
    // 查找目标会话（假设用 sessionObject 作为唯一标识）
    final targetConversation = _conversationBox.values.firstWhere(
      (conv) => conv.sessionObject == sessionId,
      orElse: () => throw Exception('Conversation not found'),
    );
    // 创建新的消息列表（原列表不可修改，需新建）
    final updatedMessages = [...targetConversation.messages, newMessage];

    // 创建更新后的会话对象（Hive 对象需要重新创建）
    final updatedConversation = targetConversation.copyWith(
      messages: updatedMessages,
      lastMessage: newMessage.content,
      lastActive: newMessage.sentAt,
    );

    // 更新 Hive 数据库
    await _conversationBox.put(sessionId, updatedConversation);
  }
}
